package com.deer.wms.ASN.manage.service.impl;

import com.deer.wms.ASN.manage.constant.AsnManageConstant;
import com.deer.wms.ASN.manage.dao.PackBillMapper;
import com.deer.wms.ASN.manage.model.pack.PackBill;
import com.deer.wms.ASN.manage.model.pack.PackBillBO;
import com.deer.wms.ASN.manage.service.PackBillService;
import com.deer.wms.inventory.model.Inventory.Inventory;
import com.deer.wms.inventory.service.InventoryService;
import com.deer.wms.project.root.service.SuperServiceImpl;
import com.deer.wms.system.manage.constant.SystemManageConstant;
import com.deer.wms.system.manage.service.CodeRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : wei
 * @since : 2021-10-27 15:02:58
 **/
@Service
@Transactional
public class PackBillServiceImpl extends SuperServiceImpl<PackBillMapper, PackBill> implements PackBillService {

    @Autowired
    private InventoryService inventoryService;
    @Autowired
    private CodeRuleService codeRuleService;

    @Override
    public void pack(List<PackBillBO> packBillBOs) {
        //1.生成组拆托记录
        String packBillCode = codeRuleService.generateCode(SystemManageConstant.CODE_RULE_PACK);
        List<PackBill> packBills = new ArrayList<>();
        for (PackBillBO bo : packBillBOs) {
            PackBill packBill = new PackBill(bo);
            packBill.setBillCode(packBillCode);
            packBills.add(packBill);
        }
        this.saveBatch(packBills);
        //2.调整库存记录信息
        List<Inventory> list = new ArrayList<>();
        for (PackBill packBill : packBills) {
            //找到每个来源容器对应的库存
            List<Inventory> sourceInventories = inventoryService.findListByField("", packBill.getBoxCode());
            for (Inventory inv : sourceInventories) {
                if (AsnManageConstant.PACK_OPER_TYPE_OUT.equals(packBill.getOperType())) {
                    //拆托
                    inv.setLpn(null);
                }else{
                    //组托-组拆拆托
                    inv.setLpn(packBill.getTargetLpn());
                }
            }
            list.addAll(sourceInventories);
        }
        inventoryService.saveBatch(list);
    }

}
